#include "plugins.h"

int loadPlugin( Plugin * p, char * fileName )
{
//	printf("Loading : %s\n", fileName);
	void * plugin = dlopen (fileName, RTLD_NOW);
	if (!plugin)
	{
		printf ("Cannot load %s: %s\n", fileName, dlerror ());
		return 1;
	}
	
	strcpy( p->fileName, fileName);
	 
    char * result = NULL;
	char * pPluginName = dlsym (plugin, "pluginName");
	
	result = dlerror ();
	if (result)
	{
                           
		strcpy( p->name, p->fileName);
		printf ("Cannot find pluginName in %s: %s", fileName, result);
	}
	else
	{
		strcpy( p->name, pPluginName);
	}
    
	char * pSubject = dlsym (plugin, "subject");
	result = dlerror ();
	if (result)
	{
		strcpy( p->subject, p->name);
		printf ("Cannot find pSubject in %s: %s", fileName, result);
	}
	else
	{
		strcpy( p->subject, pSubject);
//		p->subject = pSubject;
	}

	init_f	init = dlsym (plugin, "init");
	result = dlerror ();
	if (result)
	{
		printf ("Cannot find init in %s: %s", pPluginName, result);
		p->init = NULL;
		return 1;
	}
	else
	{
		p->init = init;
	}

	
	parse_f	parse = dlsym (plugin, "parse");
	result = dlerror ();
	if (result)
	{
		p->parse = NULL;
		printf ("Cannot find parse in %s: %s", pPluginName, result);
		return 1;
	}
	else
	{
		p->parse = parse;
	}
	
	return 0;	
}

int  loadPlugins( Plugin ** tabPlugins, char * pluginsToLoad[MAX_PLUGINS], int nbPluginsToLoad)
{
	int nbPluginsLoaded = 0;
	int i = 0;

	for ( i = 0 ; i < nbPluginsToLoad ; i ++ )
	{
		Plugin * p = (Plugin * ) malloc( sizeof( Plugin ) );
		if ( loadPlugin( p,  (char*) pluginsToLoad) == 0 )
		{
			printf("Load plugin %s Success \n", (char*)pluginsToLoad);
			if ( p->init( NULL, NULL ) )
			{
				tabPlugins[ i ] = p;
				nbPluginsLoaded ++ ;
			}
		}
		else
		{
			printf("Load plugin %s Failed \n", (char*)pluginsToLoad);
		}
		pluginsToLoad ++;
		
	}
	return nbPluginsLoaded;
}
